package web

import (
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"mts/log_srv/internal/domain"
	"mts/log_srv/internal/service"
	middleware "mts/log_srv/internal/web/middleware"
	"net/http"
	"strconv"
)

type LogHandler struct {
	logSvc service.LogService
}

func NewLogHandler(logSvc service.LogService) *LogHandler {
	return &LogHandler{logSvc: logSvc}
}
func (l LogHandler) RegisterRoutes(group *gin.RouterGroup) {
	routes := group.Use(middleware.JWTAuth())
	routes.GET("/", l.FindAllLogs)
	routes.GET("/export", l.ExportLogs)
}

func (l LogHandler) FindAllLogs(ctx *gin.Context) {
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	if list, err := l.logSvc.List(ctx, page, pageSize); err != nil {
		ctx.JSON(http.StatusOK, gin.H{"msg": "获取日志异常"})
		return
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": list})
	}
}
func (l LogHandler) ExportLogs(ctx *gin.Context) {
	if list, err := l.logSvc.List(ctx, 0, 0); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "获取日志异常"})
		return
	} else {
		l.exportExcel(ctx, list)
	}
}

func (l LogHandler) exportExcel(ctx *gin.Context, logs []*domain.Logs) {
	f := excelize.NewFile()

	// 创建一个工作表
	index, _ := f.NewSheet("Logs")

	// 写入表头
	f.SetCellValue("Logs", "A1", "用户")
	f.SetCellValue("Logs", "B1", "操作")
	f.SetCellValue("Logs", "C1", "类型")
	f.SetCellValue("Logs", "D1", "时间")
	f.SetCellValue("Logs", "E1", "详情")

	// 写入日志数据
	for i, log := range logs {
		row := i + 2 // 从第二行开始写入数据
		f.SetCellValue("Logs", "A"+strconv.Itoa(row), log.UserID)
		f.SetCellValue("Logs", "B"+strconv.Itoa(row), log.Action)
		f.SetCellValue("Logs", "C"+strconv.Itoa(row), log.Type)
		f.SetCellValue("Logs", "D"+strconv.Itoa(row), log.Timestamp)
		f.SetCellValue("Logs", "E"+strconv.Itoa(row), log.Details)
	}

	// 设置默认工作表
	f.SetActiveSheet(index)

	// 设置响应头
	ctx.Header("Content-Type", "application/octet-stream")
	ctx.Header("Content-Disposition", "attachment; filename=logs.xlsx")

	// 将 Excel 文件写入响应
	if _, err := f.WriteTo(ctx.Writer); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "导出失败"})
	}
}
